# scripts/utils.py
import os
from osgeo import gdal
import rasterio
from rasterio.mask import mask
import numpy as np


def read_and_mask_layer(subdataset_path, geometry):
    try:
        with rasterio.open(subdataset_path) as src:
            out_image, _ = mask(src, geometry, crop=True)
            return out_image[0].astype(np.float32)
    except Exception as e:
        print(f"⚠️ 读取失败: {subdataset_path}\n错误: {e}")
        return None


def check_subdatasets(hdf_path):
    hdf_path = os.path.abspath(hdf_path).replace("\\", "/")
    ds = gdal.Open(hdf_path)
    if ds is None:
        print(f"❌ 无法打开 HDF 文件: {hdf_path}")
        return
    print(f"📁 {os.path.basename(hdf_path)} 的子数据集:")
    for name, _ in ds.GetSubDatasets():
        print(f" - {name}")
